package com.example.springboot.utils.avro.vo;

import com.example.springboot.utils.avro.AvroUtils;
import com.example.springboot.utils.excel.ReflectionUtils;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.util.Utf8;
import org.apache.commons.lang.StringEscapeUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Avro2Entity<T> {

    public static void main(String[] args) throws Exception {
        String schemaName = null; // message.getLabel();
        // List<GenericRecord> genericRecords =
        // AvroUtils.deserialization(schemaName, message.getBody());
        List<GenericRecord> genericRecords = AvroUtils.deserialization(schemaName, null);
        // 过滤非空
        if (genericRecords == null || genericRecords.size() == 0) {
            return;
        }

        List<Base_IMSI> list = new Avro2Entity<Base_IMSI>().avro2javaEntity(genericRecords, Base_IMSI.class);
        if (schemaName.equals("Base_IMSI")) {
        }
    }

    public Avro2Entity() {
    }

    // 返回实体的 方式
    public List<T> avro2javaEntity(List<GenericRecord> records, Class clazz) {
        return (List<T>) avro2javaEntity(records, clazz, false);
    }

    // 返回map的 方式
    public List<Object> avro2javaMap(List<GenericRecord> records, Class clazz) {
        return avro2javaEntity(records, clazz, true);
    }

    public List<Object> avro2javaEntity(List<GenericRecord> records, Class<T> clazz, boolean isMap) {
        if (records == null || records.size() == 0) {
            return null;
        }
        List<Object> list = new ArrayList<Object>();
        for (GenericRecord r : records) {
            try {
                T o = clazz.newInstance();
                Map<String, Object> om = new HashMap<String, Object>();
                Field[] fs = clazz.getDeclaredFields();
                for (Field field : fs) {
                    String fName = field.getName();
                    Object v = r.get(fName);
                    if (v instanceof Utf8) {
                        v = StringEscapeUtils.escapeSql(v.toString());
                        om.put(fName, v);
                    }
                    if (v != null) {
                        ReflectionUtils.setFieldValue(o, fName, v);
                        om.put(fName, v);
                    }
                }
                if (!isMap) {
                    list.add(o);
                } else {
                    list.add(om);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return list;
    }
}
